home *** CD-ROM | disk | FTP | other *** search
/ Windows Expert / Windows Expert.iso / windownt / tusrc.zip / SRC / OD.C < prev    next >
C/C++ Source or Header  |  1993-09-19  |  48KB  |  1,967 lines

  1. /* od -- dump files in octal and other formats
  2.    Copyright (C) 1992 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* Written by Jim Meyering.  */
  19.  
  20. /* AIX requires this to be the first thing in the file.  */
  21. #ifdef __GNUC__
  22. #define alloca __builtin_alloca
  23. #else /* not __GNUC__ */
  24. #if HAVE_ALLOCA_H
  25. #include <malloc.h>
  26. #else /* not HAVE_ALLOCA_H */
  27. #ifdef _AIX
  28.  #pragma alloca
  29. #else /* not _AIX */
  30. char *alloca ();
  31. #endif /* not _AIX */
  32. #endif /* not HAVE_ALLOCA_H */
  33. #endif /* not __GNUC__ */
  34.  
  35. #include <stdio.h>
  36. #include <assert.h>
  37. #include "../lib/getopt.h"
  38. #include <sys/types.h>
  39. #include "system.h"
  40. #include "version.h"
  41.  
  42. #if defined(__GNUC__) || defined(STDC_HEADERS)
  43. #include <float.h>
  44. #endif
  45.  
  46. #ifdef HAVE_LONG_DOUBLE
  47. typedef long double LONG_DOUBLE;
  48. #else
  49. typedef double LONG_DOUBLE;
  50. #endif
  51.  
  52. #if HAVE_LIMITS_H
  53. #include <limits.h>
  54. #endif
  55. #ifndef SCHAR_MAX
  56. #define SCHAR_MAX 127
  57. #endif
  58. #ifndef SCHAR_MIN
  59. #define SCHAR_MIN (-128)
  60. #endif
  61. #ifndef SHRT_MAX
  62. #define SHRT_MAX 32767
  63. #endif
  64. #ifndef SHRT_MIN
  65. #define SHRT_MIN (-32768)
  66. #endif
  67. #ifndef ULONG_MAX
  68. #define ULONG_MAX ((unsigned long) ~(unsigned long) 0)
  69. #endif
  70.  
  71. #define STREQ(a,b) (strcmp((a), (b)) == 0)
  72.  
  73. #ifndef MAX
  74. #define MAX(a, b) ((a) > (b) ? (a) : (b))
  75. #endif
  76.  
  77. #ifndef MIN
  78. #define MIN(a,b) (((a) < (b)) ? (a) : (b))
  79. #endif
  80.  
  81. /* The default number of input bytes per output line.  */
  82. #define DEFAULT_BYTES_PER_BLOCK 16
  83.  
  84. /* The number of decimal digits of precision in a float.  */
  85. #ifndef FLT_DIG
  86. #define FLT_DIG 7
  87. #endif
  88.  
  89. /* The number of decimal digits of precision in a double.  */
  90. #ifndef DBL_DIG
  91. #define DBL_DIG 15
  92. #endif
  93.  
  94. /* The number of decimal digits of precision in a long double.  */
  95. #ifndef LDBL_DIG
  96. #define LDBL_DIG DBL_DIG
  97. #endif
  98.  
  99. char *xmalloc ();
  100. char *xrealloc ();
  101. void error ();
  102.  
  103. enum size_spec
  104.   {
  105.     NO_SIZE,
  106.     CHAR,
  107.     SHORT,
  108.     INT,
  109.     LONG,
  110.     FP_SINGLE,
  111.     FP_DOUBLE,
  112.     FP_LONG_DOUBLE
  113.   };
  114.  
  115. enum output_format
  116.   {
  117.     SIGNED_DECIMAL,
  118.     UNSIGNED_DECIMAL,
  119.     OCTAL,
  120.     HEXADECIMAL,
  121.     FLOATING_POINT,
  122.     NAMED_CHARACTER,
  123.     CHARACTER
  124.   };
  125.  
  126. enum strtoul_error
  127.   {
  128.     UINT_OK, UINT_INVALID, UINT_INVALID_SUFFIX_CHAR, UINT_OVERFLOW
  129.   };
  130. typedef enum strtoul_error strtoul_error;
  131.  
  132. /* Each output format specification (from POSIX `-t spec' or from
  133.    old-style options) is represented by one of these structures.  */
  134. struct tspec
  135.   {
  136.     enum output_format fmt;
  137.     enum size_spec size;
  138.     void (*print_function) ();
  139.     char *fmt_string;
  140.   };
  141.  
  142. /* The name this program was run with.  */
  143. char *program_name;
  144.  
  145. /* Convert the number of 8-bit bytes of a binary representation to
  146.    the number of characters (digits + sign if the type is signed)
  147.    required to represent the same quantity in the specified base/type.
  148.    For example, a 32-bit (4-byte) quantity may require a field width
  149.    as wide as the following for these types:
  150.    11    unsigned octal
  151.    11    signed decimal
  152.    10    unsigned decimal
  153.    8    unsigned hexadecimal  */
  154.  
  155. static const unsigned int bytes_to_oct_digits[] =
  156. {0, 3, 6, 8, 11, 14, 16, 19, 22, 25, 27, 30, 32, 35, 38, 41, 43};
  157.  
  158. static const unsigned int bytes_to_signed_dec_digits[] =
  159. {1, 4, 6, 8, 11, 13, 16, 18, 20, 23, 25, 28, 30, 33, 35, 37, 40};
  160.  
  161. static const unsigned int bytes_to_unsigned_dec_digits[] =
  162. {0, 3, 5, 8, 10, 13, 15, 17, 20, 22, 25, 27, 29, 32, 34, 37, 39};
  163.  
  164. static const unsigned int bytes_to_hex_digits[] =
  165. {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32};
  166.  
  167. /* Convert enum size_spec to the size of the named type.  */
  168. static const int width_bytes[] =
  169. {
  170.   -1,
  171.   sizeof (char),
  172.   sizeof (short int),
  173.   sizeof (int),
  174.   sizeof (long int),
  175.   sizeof (float),
  176.   sizeof (double),
  177.   sizeof (LONG_DOUBLE)
  178. };
  179.  
  180. /* Names for some non-printing characters.  */
  181. static const char *const charname[33] =
  182. {
  183.   "nul", "soh", "stx", "etx", "eot", "enq", "ack", "bel",
  184.   "bs", "ht", "nl", "vt", "ff", "cr", "so", "si",
  185.   "dle", "dc1", "dc2", "dc3", "dc4", "nak", "syn", "etb",
  186.   "can", "em", "sub", "esc", "fs", "gs", "rs", "us",
  187.   "sp"
  188. };
  189.  
  190. /* A printf control string for printing a file offset.  */
  191. static const char *output_address_fmt_string;
  192.  
  193. /* FIXME: make this the number of octal digits in an unsigned long.  */
  194. #define MAX_ADDRESS_LENGTH 13
  195.  
  196. /* Space for a normal address, a space, a pseudo address, parentheses
  197.    around the pseudo address, and a trailing zero byte. */
  198. static char address_fmt_buffer[2 * MAX_ADDRESS_LENGTH + 4];
  199. static char address_pad[MAX_ADDRESS_LENGTH + 1];
  200.  
  201. static unsigned long int string_min;
  202. static unsigned long int flag_dump_strings;
  203.  
  204. /* Non-zero if we should recognize the pre-POSIX non-option arguments
  205.    that specified at most one file and optional arguments specifying
  206.    offset and pseudo-start address.  */
  207. static int flag_compatibility;
  208.  
  209. /* Non-zero if an old-style `pseudo-address' was specified.  */
  210. static long int flag_pseudo_start;
  211.  
  212. /* The difference between the old-style pseudo starting address and
  213.    the number of bytes to skip.  */
  214. static long int pseudo_offset;
  215.  
  216. /* Function to format an address and optionally an additional parenthesized
  217.    pseudo-address; it returns the formatted string.  */
  218. static const char *(*format_address) (/* long unsigned int */);
  219.  
  220. /* The number of input bytes to skip before formatting and writing.  */
  221. static unsigned long int n_bytes_to_skip = 0;
  222.  
  223. /* When non-zero, MAX_BYTES_TO_FORMAT is the maximum number of bytes
  224.    to be read and formatted.  Otherwise all input is formatted.  */
  225. static int limit_bytes_to_format = 0;
  226.  
  227. /* The maximum number of bytes that will be formatted.  This
  228.    value is used only when LIMIT_BYTES_TO_FORMAT is non-zero.  */
  229. static unsigned long int max_bytes_to_format;
  230.  
  231. /* When non-zero and two or more consecutive blocks are equal, format
  232.    only the first block and output an asterisk alone on the following
  233.    line to indicate that identical blocks have been elided.  */
  234. static int abbreviate_duplicate_blocks = 1;
  235.  
  236. /* An array of specs describing how to format each input block.  */
  237. static struct tspec *spec;
  238.  
  239. /* The number of format specs.  */
  240. static unsigned int n_specs;
  241.  
  242. /* The allocated length of SPEC.  */
  243. static unsigned int n_specs_allocated;
  244.  
  245. /* The number of input bytes formatted per output line.  It must be
  246.    a multiple of the least common multiple of the sizes associated with
  247.    the specified output types.  It should be as large as possible, but
  248.    no larger than 16 -- unless specified with the -w option.  */
  249. static unsigned int bytes_per_block;
  250.  
  251. /* Human-readable representation of *file_list (for error messages).
  252.    It differs from *file_list only when *file_list is "-".  */
  253. static char const *input_filename;
  254.  
  255. /* A NULL-terminated list of the file-arguments from the command line.
  256.    If no file-arguments were specified, this variable is initialized
  257.    to { "-", NULL }.  */
  258. static char const *const *file_list;
  259.  
  260. /* The input stream associated with the current file.  */
  261. static FILE *in_stream;
  262.  
  263. /* If non-zero, at least one of the files we read was standard input.  */
  264. static int have_read_stdin;
  265.  
  266. #define LONGEST_INTEGRAL_TYPE long int
  267.  
  268. #define MAX_INTEGRAL_TYPE_SIZE sizeof(LONGEST_INTEGRAL_TYPE)
  269. static enum size_spec integral_type_size[MAX_INTEGRAL_TYPE_SIZE + 1];
  270.  
  271. #define MAX_FP_TYPE_SIZE sizeof(LONG_DOUBLE)
  272. static enum size_spec fp_type_size[MAX_FP_TYPE_SIZE + 1];
  273.  
  274. /* If non-zero, display usage information and exit.  */
  275. static int flag_help;
  276.  
  277. /* If non-zero, print the version on standard error.  */
  278. static int flag_version;
  279.  
  280. static struct option const long_options[] =
  281. {
  282.   /* POSIX options.  */
  283.   {"skip-bytes", required_argument, NULL, 'j'},
  284.   {"address-radix", required_argument, NULL, 'A'},
  285.   {"read-bytes", required_argument, NULL, 'N'},
  286.   {"format", required_argument, NULL, 't'},
  287.   {"output-duplicates", no_argument, NULL, 'v'},
  288.  
  289.   /* non-POSIX options.  */
  290.   {"compatible", no_argument, NULL, 'C'},
  291.   {"strings", optional_argument, NULL, 's'},
  292.   {"width", optional_argument, NULL, 'w'},
  293.   {"help", no_argument, &flag_help, 1},
  294.   {"version", no_argument, &flag_version, 1},
  295.   {NULL, 0, NULL, 0}
  296. };
  297.  
  298. static void
  299. usage ()
  300. {
  301.   fprintf (stderr, "\
  302. Usage: %s [-abcdfhiloxv] [-s[bytes]] [-w[bytes]] [-A radix] [-j bytes]\n\
  303.        [-N bytes] [-t type] [--skip-bytes=bytes] [--address-radix=radix]\n\
  304.        [--read-bytes=bytes] [--format=type] [--output-duplicates]\n\
  305.        [--strings[=bytes]] [--width[=bytes]] [--help] [--version] [file...]\n",
  306.        program_name);
  307.   exit (1);
  308. }
  309.  
  310. /* Compute the greatest common denominator of U and V
  311.    using Euclid's algorithm.  */
  312.  
  313. static unsigned int
  314. gcd (u, v)
  315.      unsigned int u;
  316.      unsigned int v;
  317. {
  318.   unsigned int t;
  319.   while (v != 0)
  320.     {
  321.       t = u % v;
  322.       u = v;
  323.       v = t;
  324.     }
  325.   return u;
  326. }
  327.  
  328. /* Compute the least common multiple of U and V.  */
  329.  
  330. static unsigned int
  331. lcm (u, v)
  332.      unsigned int u;
  333.      unsigned int v;
  334. {
  335.   unsigned int t = gcd (u, v);
  336.   if (t == 0)
  337.     return 0;
  338.   return u * v / t;
  339. }
  340.  
  341. static strtoul_error
  342. my_strtoul (s, base, val, allow_bkm_suffix)
  343.      const char *s;
  344.      int base;
  345.      long unsigned int *val;
  346.      int allow_bkm_suffix;
  347. {
  348.   char *p;
  349.   unsigned long int tmp;
  350.  
  351.   assert (0 <= base && base <= 36);
  352.  
  353.   tmp = strtoul (s, &p, base);
  354.   if (errno != 0)
  355.     return UINT_OVERFLOW;
  356.   if (p == s)
  357.     return UINT_INVALID;
  358.   if (!allow_bkm_suffix)
  359.     {
  360.       if (*p == '\0')
  361.     {
  362.       *val = tmp;
  363.       return UINT_OK;
  364.     }
  365.       else
  366.     return UINT_INVALID_SUFFIX_CHAR;
  367.     }
  368.  
  369.   switch (*p)
  370.     {
  371.     case '\0':
  372.       break;
  373.  
  374. #define BKM_SCALE(x,scale_factor,error_return)        \
  375.       do                        \
  376.     {                        \
  377.       if (x > (double) ULONG_MAX / scale_factor)    \
  378.         return error_return;            \
  379.       x *= scale_factor;                \
  380.     }                        \
  381.       while (0)
  382.  
  383.     case 'b':
  384.       BKM_SCALE (tmp, 512, UINT_OVERFLOW);
  385.       break;
  386.  
  387.     case 'k':
  388.       BKM_SCALE (tmp, 1024, UINT_OVERFLOW);
  389.       break;
  390.  
  391.     case 'm':
  392.       BKM_SCALE (tmp, 1024 * 1024, UINT_OVERFLOW);
  393.       break;
  394.  
  395.     default:
  396.       return UINT_INVALID_SUFFIX_CHAR;
  397.       break;
  398.     }
  399.  
  400.   *val = tmp;
  401.   return UINT_OK;
  402. }
  403.  
  404. static void
  405. uint_fatal_error (str, argument_type_string, err)
  406.      const char *str;
  407.      const char *argument_type_string;
  408.      strtoul_error err;
  409. {
  410.   switch (err)
  411.     {
  412.     case UINT_OK:
  413.       abort ();
  414.  
  415.     case UINT_INVALID:
  416.       error (2, 0, "invalid %s `%s'", argument_type_string, str);
  417.       break;
  418.  
  419.     case UINT_INVALID_SUFFIX_CHAR:
  420.       error (2, 0, "invalid character following %s `%s'",
  421.          argument_type_string, str);
  422.       break;
  423.  
  424.     case UINT_OVERFLOW:
  425.       error (2, 0, "%s `%s' larger than maximum unsigned long",
  426.          argument_type_string, str);
  427.       break;
  428.     }
  429. }
  430.  
  431. static void
  432. print_s_char (n_bytes, block, fmt_string)
  433.      long unsigned int n_bytes;
  434.      const char *block;
  435.      const char *fmt_string;
  436. {
  437.   int i;
  438.   for (i = n_bytes; i > 0; i--)
  439.     {
  440.       int tmp = (unsigned) *(const unsigned char *) block;
  441.       if (tmp > SCHAR_MAX)
  442.     tmp -= SCHAR_MAX - SCHAR_MIN + 1;
  443.       assert (tmp <= SCHAR_MAX);
  444.       printf (fmt_string, tmp, (i == 1 ? '\n' : ' '));
  445.       block += sizeof (unsigned char);
  446.     }
  447. }
  448.  
  449. static void
  450. print_char (n_bytes, block, fmt_string)
  451.      long unsigned int n_bytes;
  452.      const char *block;
  453.      const char *fmt_string;
  454. {
  455.   int i;
  456.   for (i = n_bytes; i > 0; i--)
  457.     {
  458.       unsigned int tmp = *(const unsigned char *) block;
  459.       printf (fmt_string, tmp, (i == 1 ? '\n' : ' '));
  460.       block += sizeof (unsigned char);
  461.     }
  462. }
  463.  
  464. static void
  465. print_s_short (n_bytes, block, fmt_string)
  466.      long unsigned int n_bytes;
  467.      const char *block;
  468.      const char *fmt_string;
  469. {
  470.   int i;
  471.   for (i = n_bytes / sizeof (unsigned short); i > 0; i--)
  472.     {
  473.       int tmp = (unsigned) *(const unsigned short *) block;
  474.       if (tmp > SHRT_MAX)
  475.     tmp -= SHRT_MAX - SHRT_MIN + 1;
  476.       assert (tmp <= SHRT_MAX);
  477.       printf (fmt_string, tmp, (i == 1 ? '\n' : ' '));
  478.       block += sizeof (unsigned short);
  479.     }
  480. }
  481. static void
  482. print_short (n_bytes, block, fmt_string)
  483.      long unsigned int n_bytes;
  484.      const char *block;
  485.      const char *fmt_string;
  486. {
  487.   int i;
  488.   for (i = n_bytes / sizeof (unsigned short); i > 0; i--)
  489.     {
  490.       unsigned int tmp = *(const unsigned short *) block;
  491.       printf (fmt_string, tmp, (i == 1 ? '\n' : ' '));
  492.       block += sizeof (unsigned short);
  493.     }
  494. }
  495.  
  496. static void
  497. print_int (n_bytes, block, fmt_string)
  498.      long unsigned int n_bytes;
  499.      const char *block;
  500.      const char *fmt_string;
  501. {
  502.   int i;
  503.   for (i = n_bytes / sizeof (unsigned int); i > 0; i--)
  504.     {
  505.       unsigned int tmp = *(const unsigned int *) block;
  506.       printf (fmt_string, tmp, (i == 1 ? '\n' : ' '));
  507.       block += sizeof (unsigned int);
  508.     }
  509. }
  510.  
  511. static void
  512. print_long (n_bytes, block, fmt_string)
  513.      long unsigned int n_bytes;
  514.      const char *block;
  515.      const char *fmt_string;
  516. {
  517.   int i;
  518.   for (i = n_bytes / sizeof (unsigned long); i > 0; i--)
  519.     {
  520.       unsigned long tmp = *(const unsigned long *) block;
  521.       printf (fmt_string, tmp, (i == 1 ? '\n' : ' '));
  522.       block += sizeof (unsigned long);
  523.     }
  524. }
  525.  
  526. static void
  527. print_float (n_bytes, block, fmt_string)
  528.      long unsigned int n_bytes;
  529.      const char *block;
  530.      const char *fmt_string;
  531. {
  532.   int i;
  533.   for (i = n_bytes / sizeof (float); i > 0; i--)
  534.     {
  535.       float tmp = *(const float *) block;
  536.       printf (fmt_string, tmp, (i == 1 ? '\n' : ' '));
  537.       block += sizeof (float);
  538.     }
  539. }
  540.  
  541. static void
  542. print_double (n_bytes, block, fmt_string)
  543.      long unsigned int n_bytes;
  544.      const char *block;
  545.      const char *fmt_string;
  546. {
  547.   int i;
  548.   for (i = n_bytes / sizeof (double); i > 0; i--)
  549.     {
  550.       double tmp = *(const double *) block;
  551.       printf (fmt_string, tmp, (i == 1 ? '\n' : ' '));
  552.       block += sizeof (double);
  553.     }
  554. }
  555.  
  556. #ifdef HAVE_LONG_DOUBLE
  557. static void
  558. print_long_double (n_bytes, block, fmt_string)
  559.      long unsigned int n_bytes;
  560.      const char *block;
  561.      const char *fmt_string;
  562. {
  563.   int i;
  564.   for (i = n_bytes / sizeof (LONG_DOUBLE); i > 0; i--)
  565.     {
  566.       LONG_DOUBLE tmp = *(const LONG_DOUBLE *) block;
  567.       printf (fmt_string, tmp, (i == 1 ? '\n' : ' '));
  568.       block += sizeof (LONG_DOUBLE);
  569.     }
  570. }
  571.  
  572. #endif
  573.  
  574. static void
  575. print_named_ascii (n_bytes, block, unused_fmt_string)
  576.      long unsigned int n_bytes;
  577.      const char *block;
  578.      const char *unused_fmt_string;
  579. {
  580.   int i;
  581.   for (i = n_bytes; i > 0; i--)
  582.     {
  583.       unsigned int c = *(const unsigned char *) block;
  584.       unsigned int masked_c = (0x7f & c);
  585.       const char *s;
  586.       char buf[5];
  587.  
  588.       if (masked_c == 127)
  589.     s = "del";
  590.       else if (masked_c <= 040)
  591.     s = charname[masked_c];
  592.       else
  593.     {
  594.       sprintf (buf, "  %c", masked_c);
  595.       s = buf;
  596.     }
  597.  
  598.       printf ("%3s%c", s, (i == 1 ? '\n' : ' '));
  599.       block += sizeof (unsigned char);
  600.     }
  601. }
  602.  
  603. static void
  604. print_ascii (n_bytes, block, unused_fmt_string)
  605.      long unsigned int n_bytes;
  606.      const char *block;
  607.      const char *unused_fmt_string;
  608. {
  609.   int i;
  610.   for (i = n_bytes; i > 0; i--)
  611.     {
  612.       unsigned int c = *(const unsigned char *) block;
  613.       const char *s;
  614.       char buf[5];
  615.  
  616.       switch (c)
  617.     {
  618.     case '\0':
  619.       s = " \\0";
  620.       break;
  621.  
  622.     case '\007':
  623.       s = " \\a";
  624.       break;
  625.  
  626.     case '\b':
  627.       s = " \\b";
  628.       break;
  629.  
  630.     case '\f':
  631.       s = " \\f";
  632.       break;
  633.  
  634.     case '\n':
  635.       s = " \\n";
  636.       break;
  637.  
  638.     case '\r':
  639.       s = " \\r";
  640.       break;
  641.  
  642.     case '\t':
  643.       s = " \\t";
  644.       break;
  645.  
  646.     case '\v':
  647.       s = " \\v";
  648.       break;
  649.  
  650.     default:
  651.       sprintf (buf, (ISPRINT (c) ? "  %c" : "%03o"), c);
  652.       s = (const char *) buf;
  653.     }
  654.  
  655.       printf ("%3s%c", s, (i == 1 ? '\n' : ' '));
  656.       block += sizeof (unsigned char);
  657.     }
  658. }
  659.  
  660. /* Convert a null-terminated (possibly zero-length) string S to an
  661.    unsigned long integer value.  If S points to a non-digit set *P to S,
  662.    *VAL to 0, and return 0.  Otherwise, accumulate the integer value of
  663.    the string of digits.  If the string of digits represents a value
  664.    larger than ULONG_MAX, don't modify *VAL or *P and return non-zero.
  665.    Otherwise, advance *P to the first non-digit after S, set *VAL to
  666.    the result of the conversion and return zero.  */
  667.  
  668. static int
  669. simple_strtoul (s, p, val)
  670.      const char *s;
  671.      const char **p;
  672.      long unsigned int *val;
  673. {
  674.   unsigned long int sum;
  675.  
  676.   sum = 0;
  677.   while (ISDIGIT (*s))
  678.     {
  679.       unsigned int c = *s++ - '0';
  680.       if (sum > (ULONG_MAX - c) / 10)
  681.     return 1;
  682.       sum = sum * 10 + c;
  683.     }
  684.   *p = s;
  685.   *val = sum;
  686.   return 0;
  687. }
  688.  
  689. /* If S points to a single valid POSIX-style od format string, put a
  690.    description of that format in *TSPEC, make *NEXT point at the character
  691.    following the just-decoded format (if *NEXT is non-NULL), and return
  692.    zero.  If S is not valid, don't modify *NEXT or *TSPEC and return
  693.    non-zero.  For example, if S were "d4afL" *NEXT would be set to "afL"
  694.    and *TSPEC would be
  695.      {
  696.        fmt = SIGNED_DECIMAL;
  697.        size = INT or LONG; (whichever integral_type_size[4] resolves to)
  698.        print_function = print_int; (assuming size == INT)
  699.        fmt_string = "%011d%c";
  700.       }
  701.    */
  702.  
  703. static int
  704. decode_one_format (s, next, tspec)
  705.      const char *s;
  706.      const char **next;
  707.      struct tspec *tspec;
  708. {
  709.   enum size_spec size_spec;
  710.   unsigned long int size;
  711.   enum output_format fmt;
  712.   const char *pre_fmt_string;
  713.   char *fmt_string;
  714.   void (*print_function) ();
  715.   const char *p;
  716.   unsigned int c;
  717.  
  718.   assert (tspec != NULL);
  719.  
  720.   switch (*s)
  721.     {
  722.     case 'd':
  723.     case 'o':
  724.     case 'u':
  725.     case 'x':
  726.       c = *s;
  727.       ++s;
  728.       switch (*s)
  729.     {
  730.     case 'C':
  731.       ++s;
  732.       size = sizeof (char);
  733.       break;
  734.  
  735.     case 'S':
  736.       ++s;
  737.       size = sizeof (short);
  738.       break;
  739.  
  740.     case 'I':
  741.       ++s;
  742.       size = sizeof (int);
  743.       break;
  744.  
  745.     case 'L':
  746.       ++s;
  747.       size = sizeof (long int);
  748.       break;
  749.  
  750.     default:
  751.       if (simple_strtoul (s, &p, &size) != 0)
  752.         return 1;
  753.       if (p == s)
  754.         size = sizeof (int);
  755.       else
  756.         {
  757.           if (size > MAX_INTEGRAL_TYPE_SIZE
  758.           || integral_type_size[size] == NO_SIZE)
  759.         return 1;
  760.           s = p;
  761.         }
  762.       break;
  763.     }
  764.  
  765. #define FMT_BYTES_ALLOCATED 9
  766.       fmt_string = xmalloc (FMT_BYTES_ALLOCATED);
  767.  
  768.       size_spec = integral_type_size[size];
  769.  
  770.       switch (c)
  771.     {
  772.     case 'd':
  773.       fmt = SIGNED_DECIMAL;
  774.       sprintf (fmt_string, "%%%u%sd%%c",
  775.            bytes_to_signed_dec_digits[size],
  776.            (size_spec == LONG ? "l" : ""));
  777.       break;
  778.  
  779.     case 'o':
  780.       fmt = OCTAL;
  781.       sprintf (fmt_string, "%%0%u%so%%c",
  782.            bytes_to_oct_digits[size],
  783.            (size_spec == LONG ? "l" : ""));
  784.       break;
  785.  
  786.     case 'u':
  787.       fmt = UNSIGNED_DECIMAL;
  788.       sprintf (fmt_string, "%%%u%su%%c",
  789.            bytes_to_unsigned_dec_digits[size],
  790.            (size_spec == LONG ? "l" : ""));
  791.       break;
  792.  
  793.     case 'x':
  794.       fmt = HEXADECIMAL;
  795.       sprintf (fmt_string, "%%0%u%sx%%c",
  796.            bytes_to_hex_digits[size],
  797.            (size_spec == LONG ? "l" : ""));
  798.       break;
  799.  
  800.     default:
  801.       abort ();
  802.     }
  803.  
  804.       assert (strlen (fmt_string) < FMT_BYTES_ALLOCATED);
  805.  
  806.       switch (size_spec)
  807.     {
  808.     case CHAR:
  809.       print_function = (fmt == SIGNED_DECIMAL
  810.                 ? print_s_char
  811.                 : print_char);
  812.       break;
  813.  
  814.     case SHORT:
  815.       print_function = (fmt == SIGNED_DECIMAL
  816.                 ? print_s_short
  817.                 : print_short);;
  818.       break;
  819.  
  820.     case INT:
  821.       print_function = print_int;
  822.       break;
  823.  
  824.     case LONG:
  825.       print_function = print_long;
  826.       break;
  827.  
  828.     default:
  829.       abort ();
  830.     }
  831.       break;
  832.  
  833.     case 'f':
  834.       fmt = FLOATING_POINT;
  835.       ++s;
  836.       switch (*s)
  837.     {
  838.     case 'F':
  839.       ++s;
  840.       size = sizeof (float);
  841.       break;
  842.  
  843.     case 'D':
  844.       ++s;
  845.       size = sizeof (double);
  846.       break;
  847.  
  848.     case 'L':
  849.       ++s;
  850.       size = sizeof (LONG_DOUBLE);
  851.       break;
  852.  
  853.     default:
  854.       if (simple_strtoul (s, &p, &size) != 0)
  855.         return 1;
  856.       if (p == s)
  857.         size = sizeof (double);
  858.       else
  859.         {
  860.           if (size > MAX_FP_TYPE_SIZE
  861.           || fp_type_size[size] == NO_SIZE)
  862.         return 1;
  863.           s = p;
  864.         }
  865.       break;
  866.     }
  867.       size_spec = fp_type_size[size];
  868.  
  869.       switch (size_spec)
  870.     {
  871.     case FP_SINGLE:
  872.       print_function = print_float;
  873.       /* Don't use %#e; not all systems support it.  */
  874.       pre_fmt_string = "%%%d.%de%%c";
  875.       fmt_string = xmalloc (strlen (pre_fmt_string));
  876.       sprintf (fmt_string, pre_fmt_string,
  877.            FLT_DIG + 8, FLT_DIG);
  878.       break;
  879.  
  880.     case FP_DOUBLE:
  881.       print_function = print_double;
  882.       pre_fmt_string = "%%%d.%de%%c";
  883.       fmt_string = xmalloc (strlen (pre_fmt_string));
  884.       sprintf (fmt_string, pre_fmt_string,
  885.            DBL_DIG + 8, DBL_DIG);
  886.       break;
  887.  
  888. #ifdef HAVE_LONG_DOUBLE
  889.     case FP_LONG_DOUBLE:
  890.       print_function = print_long_double;
  891.       pre_fmt_string = "%%%d.%dle%%c";
  892.       fmt_string = xmalloc (strlen (pre_fmt_string));
  893.       sprintf (fmt_string, pre_fmt_string,
  894.            LDBL_DIG + 8, LDBL_DIG);
  895.       break;
  896. #endif
  897.  
  898.     default:
  899.       abort ();
  900.     }
  901.       break;
  902.  
  903.     case 'a':
  904.       ++s;
  905.       fmt = NAMED_CHARACTER;
  906.       size_spec = CHAR;
  907.       fmt_string = NULL;
  908.       print_function = print_named_ascii;
  909.       break;
  910.  
  911.     case 'c':
  912.       ++s;
  913.       fmt = CHARACTER;
  914.       size_spec = CHAR;
  915.       fmt_string = NULL;
  916.       print_function = print_ascii;
  917.       break;
  918.  
  919.     default:
  920.       return 1;
  921.     }
  922.  
  923.   tspec->size = size_spec;
  924.   tspec->fmt = fmt;
  925.   tspec->print_function = print_function;
  926.   tspec->fmt_string = fmt_string;
  927.  
  928.   if (next != NULL)
  929.     *next = s;
  930.  
  931.   return 0;
  932. }
  933.  
  934. /* Decode the POSIX-style od format string S.  Append the decoded
  935.    representation to the global array SPEC, reallocating SPEC if
  936.    necessary.  Return zero if S is valid, non-zero otherwise.  */
  937.  
  938. static int
  939. decode_format_string (s)
  940.      const char *s;
  941. {
  942.   assert (s != NULL);
  943.  
  944.   while (*s != '\0')
  945.     {
  946.       struct tspec tspec;
  947.       const char *next;
  948.  
  949.       if (decode_one_format (s, &next, &tspec))
  950.     return 1;
  951.  
  952.       assert (s != next);
  953.       s = next;
  954.  
  955.       if (n_specs >= n_specs_allocated)
  956.     {
  957.       n_specs_allocated = 1 + (3 * n_specs_allocated) / 2;
  958.       spec = (struct tspec *) xrealloc (spec, (n_specs_allocated
  959.                            * sizeof (struct tspec)));
  960.     }
  961.  
  962.       bcopy ((char *) &tspec, (char *) &spec[n_specs], sizeof (struct tspec));
  963.       ++n_specs;
  964.     }
  965.  
  966.   return 0;
  967. }
  968.  
  969. /* Given a list of one or more input filenames FILE_LIST, set the global
  970.    file pointer IN_STREAM to position N_SKIP in the concatenation of
  971.    those files.  If any file operation fails or if there are fewer than
  972.    N_SKIP bytes in the combined input, give an error message and exit.
  973.    When possible, use seek- rather than read operations to advance
  974.    IN_STREAM.  A file name of "-" is interpreted as standard input.  */
  975.  
  976. static int
  977. skip (n_skip)
  978.      long unsigned int n_skip;
  979. {
  980.   int err;
  981.  
  982.   err = 0;
  983.   for ( /* empty */ ; *file_list != NULL; ++file_list)
  984.     {
  985.       struct stat file_stats;
  986.       int j;
  987.  
  988.       if (STREQ (*file_list, "-"))
  989.     {
  990.       input_filename = "standard input";
  991.       in_stream = stdin;
  992.       have_read_stdin = 1;
  993.     }
  994.       else
  995.     {
  996.       input_filename = *file_list;
  997.       in_stream = fopen (input_filename, "r");
  998.       if (in_stream == NULL)
  999.         {
  1000.           error (0, errno, "%s", input_filename);
  1001.           err = 1;
  1002.           continue;
  1003.         }
  1004.     }
  1005.  
  1006.       if (n_skip == 0)
  1007.     break;
  1008.  
  1009.       /* First try using fseek.  For large offsets, this extra work is
  1010.      worthwhile.  If the offset is below some threshold it may be
  1011.      more efficient to move the pointer by reading.  There are two
  1012.      issues when trying to use fseek:
  1013.        - the file must be seekable.
  1014.        - before seeking to the specified position, make sure
  1015.          that the new position is in the current file.
  1016.          Try to do that by getting file's size using stat().
  1017.          But that will work only for regular files and dirs.  */
  1018.  
  1019.       if (fstat (fileno (in_stream), &file_stats))
  1020.     {
  1021.       error (0, errno, "%s", input_filename);
  1022.       err = 1;
  1023.       continue;
  1024.     }
  1025.  
  1026.       /* The st_size field is valid only for regular files and
  1027.      directories.  FIXME: is the preceding true?
  1028.      If the number of bytes left to skip is at least as large as
  1029.      the size of the current file, we can decrement
  1030.      n_skip and go on to the next file.  */
  1031.       if (S_ISREG (file_stats.st_mode) || S_ISDIR (file_stats.st_mode))
  1032.     {
  1033.       if (n_skip >= (unsigned) file_stats.st_size)
  1034.         {
  1035.           n_skip -= file_stats.st_size;
  1036.           if (in_stream != stdin && fclose (in_stream) == EOF)
  1037.         {
  1038.           error (0, errno, "%s", input_filename);
  1039.           err = 1;
  1040.         }
  1041.           continue;
  1042.         }
  1043.       else
  1044.         {
  1045.           if (fseek (in_stream, n_skip, SEEK_SET) == 0)
  1046.         {
  1047.           n_skip = 0;
  1048.           break;
  1049.         }
  1050.         }
  1051.     }
  1052.  
  1053.       /* fseek didn't work or wasn't attempted; do it the slow way.  */
  1054.  
  1055.       for (j = n_skip / BUFSIZ; j >= 0; j--)
  1056.     {
  1057.       char buf[BUFSIZ];
  1058.       size_t n_bytes_to_read = (j > 0
  1059.                     ? BUFSIZ
  1060.                     : n_skip % BUFSIZ);
  1061.       size_t n_bytes_read;
  1062.       n_bytes_read = fread (buf, 1, n_bytes_to_read, in_stream);
  1063.       n_skip -= n_bytes_read;
  1064.       if (n_bytes_read != n_bytes_to_read)
  1065.         break;
  1066.     }
  1067.  
  1068.       if (n_skip == 0)
  1069.     break;
  1070.     }
  1071.  
  1072.   if (n_skip != 0)
  1073.     error (2, 0, "cannot skip past end of combined input");
  1074.  
  1075.   return err;
  1076. }
  1077.  
  1078. static const char *
  1079. format_address_none (address)
  1080.      long unsigned int address;
  1081. {
  1082.   return "";
  1083. }
  1084.  
  1085. static const char *
  1086. format_address_std (address)
  1087.      long unsigned int address;
  1088. {
  1089.   const char *address_string;
  1090.  
  1091.   sprintf (address_fmt_buffer, output_address_fmt_string, address);
  1092.   address_string = address_fmt_buffer;
  1093.   return address_string;
  1094. }
  1095.  
  1096. static const char *
  1097. format_address_label (address)
  1098.      long unsigned int address;
  1099. {
  1100.   const char *address_string;
  1101.   assert (output_address_fmt_string != NULL);
  1102.  
  1103.   sprintf (address_fmt_buffer, output_address_fmt_string,
  1104.        address, address + pseudo_offset);
  1105.   address_string = address_fmt_buffer;
  1106.   return address_string;
  1107. }
  1108.  
  1109. /* Write N_BYTES bytes from CURR_BLOCK to standard output once for each
  1110.    of the N_SPEC format specs.  CURRENT_OFFSET is the byte address of
  1111.    CURR_BLOCK in the concatenation of input files, and it is printed
  1112.    (optionally) only before the output line associated with the first
  1113.    format spec.  When duplicate blocks are being abbreviated, the output
  1114.    for a sequence of identical input blocks is the output for the first
  1115.    block followed by an asterisk alone on a line.  It is valid to compare
  1116.    the blocks PREV_BLOCK and CURR_BLOCK only when N_BYTES == BYTES_PER_BLOCK.
  1117.    That condition may be false only for the last input block -- and then
  1118.    only when it has not been padded to length BYTES_PER_BLOCK.  */
  1119.  
  1120. static void
  1121. write_block (current_offset, n_bytes, prev_block, curr_block)
  1122.      long unsigned int current_offset;
  1123.      long unsigned int n_bytes;
  1124.      const char *prev_block;
  1125.      const char *curr_block;
  1126. {
  1127.   static int first = 1;
  1128.   static int prev_pair_equal = 0;
  1129.  
  1130. #define EQUAL_BLOCKS(b1, b2) (bcmp ((b1), (b2), bytes_per_block) == 0)
  1131.  
  1132.   if (abbreviate_duplicate_blocks
  1133.       && !first && n_bytes == bytes_per_block
  1134.       && EQUAL_BLOCKS (prev_block, curr_block))
  1135.     {
  1136.       if (prev_pair_equal)
  1137.     {
  1138.       /* The two preceding blocks were equal, and the current
  1139.          block is the same as the last one, so print nothing.  */
  1140.     }
  1141.       else
  1142.     {
  1143.       printf ("*\n");
  1144.       prev_pair_equal = 1;
  1145.     }
  1146.     }
  1147.   else
  1148.     {
  1149.       int i;
  1150.  
  1151.       prev_pair_equal = 0;
  1152.       for (i = 0; (unsigned) i < n_specs; i++)
  1153.     {
  1154.       printf ("%s ", (i == 0
  1155.               ? format_address (current_offset)
  1156.               : address_pad));
  1157.       (*spec[i].print_function) (n_bytes, curr_block, spec[i].fmt_string);
  1158.     }
  1159.     }
  1160.   first = 0;
  1161. }
  1162.  
  1163. /* Test whether there have been errors on in_stream, and close it if
  1164.    it is not standard input.  Return non-zero if there has been an error
  1165.    on in_stream or stdout; return zero otherwise.  This function will
  1166.    report more than one error only if both a read and a write error
  1167.    have occurred.  */
  1168.  
  1169. static int
  1170. check_and_close ()
  1171. {
  1172.   int err;
  1173.  
  1174.   err = 0;
  1175.   if (ferror (in_stream))
  1176.     {
  1177.       error (0, errno, "%s", input_filename);
  1178.       if (in_stream != stdin)
  1179.     fclose (in_stream);
  1180.       err = 1;
  1181.     }
  1182.   else if (in_stream != stdin && fclose (in_stream) == EOF)
  1183.     {
  1184.       error (0, errno, "%s", input_filename);
  1185.       err = 1;
  1186.     }
  1187.  
  1188.   if (ferror (stdout))
  1189.     {
  1190.       error (0, errno, "standard output");
  1191.       err = 1;
  1192.     }
  1193.  
  1194.   return err;
  1195. }
  1196.  
  1197. /* Read a single byte into *C from the concatenation of the input files
  1198.    named in the global array FILE_LIST.  On the first call to this
  1199.    function, the global variable IN_STREAM is expected to be an open
  1200.    stream associated with the input file *FILE_LIST.  If IN_STREAM is
  1201.    at end-of-file, close it and update the global variables IN_STREAM,
  1202.    FILE_LIST, and INPUT_FILENAME so they correspond to the next file in
  1203.    the list.  Then try to read a byte from the newly opened file.
  1204.    Repeat if necessary until *FILE_LIST is NULL.  When EOF is reached
  1205.    for the last file in FILE_LIST, set *C to EOF and return.  Subsequent
  1206.    calls do likewise.  The return value is non-zero if any errors
  1207.    occured, zero otherwise.  */
  1208.  
  1209. static int
  1210. read_char (c)
  1211.      int *c;
  1212. {
  1213.   int err;
  1214.  
  1215.   if (*file_list == NULL)
  1216.     {
  1217.       *c = EOF;
  1218.       return 0;
  1219.     }
  1220.  
  1221.   err = 0;
  1222.   while (1)
  1223.     {
  1224.       *c = fgetc (in_stream);
  1225.  
  1226.       if (*c != EOF)
  1227.     return err;
  1228.  
  1229.       err |= check_and_close ();
  1230.  
  1231.       do
  1232.     {
  1233.       ++file_list;
  1234.       if (*file_list == NULL)
  1235.         return err;
  1236.  
  1237.       if (STREQ (*file_list, "-"))
  1238.         {
  1239.           input_filename = "standard input";
  1240.           in_stream = stdin;
  1241.           have_read_stdin = 1;
  1242.         }
  1243.       else
  1244.         {
  1245.           input_filename = *file_list;
  1246.           in_stream = fopen (input_filename, "r");
  1247.           if (in_stream == NULL)
  1248.         {
  1249.           error (0, errno, "%s", input_filename);
  1250.           err = 1;
  1251.         }
  1252.         }
  1253.     }
  1254.       while (in_stream == NULL);
  1255.     }
  1256. }
  1257.  
  1258. /* Read N bytes into BLOCK from the concatenation of the input files
  1259.    named in the global array FILE_LIST.  On the first call to this
  1260.    function, the global variable IN_STREAM is expected to be an open
  1261.    stream associated with the input file *FILE_LIST.  On subsequent
  1262.    calls, if *FILE_LIST is NULL, don't modify BLOCK and return zero.
  1263.    If all N bytes cannot be read from IN_STREAM, close IN_STREAM and
  1264.    update the global variables IN_STREAM, FILE_LIST, and INPUT_FILENAME.
  1265.    Then try to read the remaining bytes from the newly opened file.
  1266.    Repeat if necessary until *FILE_LIST is NULL.  Set *N_BYTES_IN_BUFFER
  1267.    to the number of bytes read.  If an error occurs, it will be detected
  1268.    through ferror when the stream is about to be closed.  If there is an
  1269.    error, give a message but continue reading as usual and return non-zero.
  1270.    Otherwise return zero.  */
  1271.  
  1272. static int
  1273. read_block (n, block, n_bytes_in_buffer)
  1274.      size_t n;
  1275.      char *block;
  1276.      size_t *n_bytes_in_buffer;
  1277. {
  1278.   int err;
  1279.  
  1280.   assert (n > 0 && n <= bytes_per_block);
  1281.  
  1282.   *n_bytes_in_buffer = 0;
  1283.  
  1284.   if (n == 0)
  1285.     return 0;
  1286.  
  1287.   if (*file_list == NULL)
  1288.     return 0;            /* EOF.  */
  1289.  
  1290.   err = 0;
  1291.   while (1)
  1292.     {
  1293.       size_t n_needed;
  1294.       size_t n_read;
  1295.  
  1296.       n_needed = n - *n_bytes_in_buffer;
  1297.       n_read = fread (block + *n_bytes_in_buffer, 1, n_needed, in_stream);
  1298.  
  1299.       *n_bytes_in_buffer += n_read;
  1300.  
  1301.       if (n_read == n_needed)
  1302.     return err;
  1303.  
  1304.       err |= check_and_close ();
  1305.  
  1306.       do
  1307.     {
  1308.       ++file_list;
  1309.       if (*file_list == NULL)
  1310.         return err;
  1311.  
  1312.       if (STREQ (*file_list, "-"))
  1313.         {
  1314.           input_filename = "standard input";
  1315.           in_stream = stdin;
  1316.           have_read_stdin = 1;
  1317.         }
  1318.       else
  1319.         {
  1320.           input_filename = *file_list;
  1321.           in_stream = fopen (input_filename, "r");
  1322.           if (in_stream == NULL)
  1323.         {
  1324.           error (0, errno, "%s", input_filename);
  1325.           err = 1;
  1326.         }
  1327.         }
  1328.     }
  1329.       while (in_stream == NULL);
  1330.     }
  1331. }
  1332.  
  1333. /* Return the least common multiple of the sizes associated
  1334.    with the format specs.  */
  1335.  
  1336. static int
  1337. get_lcm ()
  1338. {
  1339.   int i;
  1340.   int l_c_m = 1;
  1341.  
  1342.   for (i = 0; (unsigned) i < n_specs; i++)
  1343.     l_c_m = lcm (l_c_m, width_bytes[(int) spec[i].size]);
  1344.   return l_c_m;
  1345. }
  1346.  
  1347. /* If S is a valid pre-POSIX offset specification with an optional leading '+'
  1348.    return the offset it denotes.  Otherwise, return -1.  */
  1349.  
  1350. long int
  1351. parse_old_offset (s)
  1352.      const char *s;
  1353. {
  1354.   int radix;
  1355.   char *suffix;
  1356.   long offset;
  1357.  
  1358.   if (*s == '\0')
  1359.     return -1;
  1360.  
  1361.   /* Skip over any leading '+'. */
  1362.   if (s[0] == '+')
  1363.     ++s;
  1364.  
  1365.   /* Determine the radix we'll use to interpret S.  If there is a `.',
  1366.      it's decimal, otherwise, if the string begins with `0X'or `0x',
  1367.      it's hexadecimal, else octal.  */
  1368.   if (index (s, '.') != NULL)
  1369.     radix = 10;
  1370.   else
  1371.     {
  1372.       if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X'))
  1373.     radix = 16;
  1374.       else
  1375.     radix = 8;
  1376.     }
  1377.   offset = strtoul (s, &suffix, radix);
  1378.   if (suffix == s || errno != 0)
  1379.     return -1;
  1380.   if (*suffix == '.')
  1381.     ++suffix;
  1382.   switch (*suffix)
  1383.     {
  1384.     case 'b':
  1385.       BKM_SCALE (offset, 512, -1);
  1386.       ++suffix;
  1387.       break;
  1388.  
  1389.     case 'B':
  1390.       BKM_SCALE (offset, 1024, -1);
  1391.       ++suffix;
  1392.       break;
  1393.  
  1394.     default:
  1395.       /* empty */
  1396.       break;
  1397.     }
  1398.  
  1399.   if (*suffix != '\0')
  1400.     return -1;
  1401.   else
  1402.     return offset;
  1403. }
  1404.  
  1405. /* Read a chunk of size BYTES_PER_BLOCK from the input files, write the
  1406.    formatted block to standard output, and repeat until the specified
  1407.    maximum number of bytes has been read or until all input has been
  1408.    processed.  If the last block read is smaller than BYTES_PER_BLOCK
  1409.    and its size is not a multiple of the size associated with a format
  1410.    spec, extend the input block with zero bytes until its length is a
  1411.    multiple of all format spec sizes.  Write the final block.  Finally,
  1412.    write on a line by itself the offset of the byte after the last byte
  1413.    read.  Accumulate return values from calls to read_block and
  1414.    check_and_close, and if any was non-zero, return non-zero.
  1415.    Otherwise, return zero.  */
  1416.  
  1417. static int
  1418. dump ()
  1419. {
  1420.   char *block[2];
  1421.   unsigned long int current_offset;
  1422.   int idx;
  1423.   int err;
  1424.   size_t n_bytes_read;
  1425.   size_t end_offset;
  1426.  
  1427.   block[0] = (char *) alloca (bytes_per_block);
  1428.   block[1] = (char *) alloca (bytes_per_block);
  1429.  
  1430.   current_offset = n_bytes_to_skip;
  1431.  
  1432.   idx = 0;
  1433.   err = 0;
  1434.   if (limit_bytes_to_format)
  1435.     {
  1436.       end_offset = n_bytes_to_skip + max_bytes_to_format;
  1437.  
  1438.       n_bytes_read = 0;
  1439.       while (current_offset < end_offset)
  1440.     {
  1441.       size_t n_needed;
  1442.       n_needed = MIN (end_offset - current_offset, bytes_per_block);
  1443.       err |= read_block (n_needed, block[idx], &n_bytes_read);
  1444.       if (n_bytes_read < bytes_per_block)
  1445.         break;
  1446.       assert (n_bytes_read == bytes_per_block);
  1447.       write_block (current_offset, n_bytes_read,
  1448.                block[!idx], block[idx]);
  1449.       current_offset += n_bytes_read;
  1450.       idx = !idx;
  1451.     }
  1452.     }
  1453.   else
  1454.     {
  1455.       while (1)
  1456.     {
  1457.       err |= read_block (bytes_per_block, block[idx], &n_bytes_read);
  1458.       if (n_bytes_read < bytes_per_block)
  1459.         break;
  1460.       assert (n_bytes_read == bytes_per_block);
  1461.       write_block (current_offset, n_bytes_read,
  1462.                block[!idx], block[idx]);
  1463.       current_offset += n_bytes_read;
  1464.       idx = !idx;
  1465.     }
  1466.     }
  1467.  
  1468.   if (n_bytes_read > 0)
  1469.     {
  1470.       int l_c_m;
  1471.       size_t bytes_to_write;
  1472.  
  1473.       l_c_m = get_lcm ();
  1474.  
  1475.       /* Make bytes_to_write the smallest multiple of l_c_m that
  1476.      is at least as large as n_bytes_read.  */
  1477.       bytes_to_write = l_c_m * (int) ((n_bytes_read + l_c_m - 1) / l_c_m);
  1478.  
  1479.       bzero (block[idx] + n_bytes_read, bytes_to_write - n_bytes_read);
  1480.       write_block (current_offset, bytes_to_write,
  1481.            block[!idx], block[idx]);
  1482.       current_offset += n_bytes_read;
  1483.     }
  1484.  
  1485.   if (output_address_fmt_string != NULL)
  1486.     printf ("%s\n", format_address (current_offset));
  1487.  
  1488.   if (limit_bytes_to_format && current_offset > end_offset)
  1489.     err |= check_and_close ();
  1490.  
  1491.   return err;
  1492. }
  1493.  
  1494. /* STRINGS mode.  Find each "string constant" in the input.
  1495.    A string constant is a run of at least `string_min' ASCII
  1496.    graphic (or formatting) characters terminated by a null.
  1497.    Based on a function written by Richard Stallman for a
  1498.    pre-POSIX version of od.  Return non-zero if an error
  1499.    occurs.  Otherwise, return zero.  */
  1500.  
  1501. static int
  1502. dump_strings ()
  1503. {
  1504.   int bufsize = MAX (100, string_min);
  1505.   char *buf = xmalloc (bufsize);
  1506.   unsigned long address = n_bytes_to_skip;
  1507.   int err;
  1508.  
  1509.   err = 0;
  1510.   while (1)
  1511.     {
  1512.       int i;
  1513.       int c;
  1514.  
  1515.       /* See if the next `string_min' chars are all printing chars.  */
  1516.     tryline:
  1517.  
  1518.       if (limit_bytes_to_format
  1519.       && address >= (n_bytes_to_skip + max_bytes_to_format - string_min))
  1520.     break;
  1521.  
  1522.       for (i = 0; (unsigned) i < string_min; i++)
  1523.     {
  1524.       err |= read_char (&c);
  1525.       address++;
  1526.       if (c < 0)
  1527.         {
  1528.           free (buf);
  1529.           return err;
  1530.         }
  1531.       if (!ISPRINT (c))
  1532.         /* Found a non-printing.  Try again starting with next char.  */
  1533.         goto tryline;
  1534.       buf[i] = c;
  1535.     }
  1536.  
  1537.       /* We found a run of `string_min' printable characters.
  1538.      Now see if it is terminated with a null byte.  */
  1539.       while (!limit_bytes_to_format
  1540.          || address < n_bytes_to_skip + max_bytes_to_format)
  1541.     {
  1542.       if (i == bufsize)
  1543.         {
  1544.           bufsize = 1 + 3 * bufsize / 2;
  1545.           buf = xrealloc (buf, bufsize);
  1546.         }
  1547.       err |= read_char (&c);
  1548.       address++;
  1549.       if (c < 0)
  1550.         {
  1551.           free (buf);
  1552.           return err;
  1553.         }
  1554.       if (c == '\0')
  1555.         break;        /* It is; print this string.  */
  1556.       if (!ISPRINT (c))
  1557.         goto tryline;    /* It isn't; give up on this string.  */
  1558.       buf[i++] = c;        /* String continues; store it all.  */
  1559.     }
  1560.  
  1561.       /* If we get here, the string is all printable and null-terminated,
  1562.      so print it.  It is all in `buf' and `i' is its length.  */
  1563.       buf[i] = 0;
  1564.       if (output_address_fmt_string != NULL)
  1565.     {
  1566.       printf ("%s ", format_address (address - i - 1));
  1567.     }
  1568.       for (i = 0; (c = buf[i]); i++)
  1569.     {
  1570.       switch (c)
  1571.         {
  1572.         case '\007':
  1573.           fputs ("\\a", stdout);
  1574.           break;
  1575.  
  1576.         case '\b':
  1577.           fputs ("\\b", stdout);
  1578.           break;
  1579.  
  1580.         case '\f':
  1581.           fputs ("\\f", stdout);
  1582.           break;
  1583.  
  1584.         case '\n':
  1585.           fputs ("\\n", stdout);
  1586.           break;
  1587.  
  1588.         case '\r':
  1589.           fputs ("\\r", stdout);
  1590.           break;
  1591.  
  1592.         case '\t':
  1593.           fputs ("\\t", stdout);
  1594.           break;
  1595.  
  1596.         case '\v':
  1597.           fputs ("\\v", stdout);
  1598.           break;
  1599.  
  1600.         default:
  1601.           putc (c, stdout);
  1602.         }
  1603.     }
  1604.       putchar ('\n');
  1605.     }
  1606.  
  1607.   /* We reach this point only if we search through
  1608.      (max_bytes_to_format - string_min) bytes before reachine EOF.  */
  1609.  
  1610.   free (buf);
  1611.  
  1612.   err |= check_and_close ();
  1613.   return err;
  1614. }
  1615.  
  1616. int
  1617. main (argc, argv)
  1618.      int argc;
  1619.      char **argv;
  1620. {
  1621.   int c;
  1622.   int n_files;
  1623.   int i;
  1624.   unsigned int l_c_m;
  1625.   unsigned int address_pad_len;
  1626.   unsigned long int desired_width;
  1627.   int width_specified = 0;
  1628.   int err;
  1629.  
  1630.   /* The old-style `pseudo starting address' to be printed in parentheses
  1631.      after any true address.  */
  1632.   long int pseudo_start;
  1633.  
  1634.   program_name = argv[0];
  1635.   err = 0;
  1636.  
  1637.   for (i = 0; i <= MAX_INTEGRAL_TYPE_SIZE; i++)
  1638.     integral_type_size[i] = NO_SIZE;
  1639.  
  1640.   integral_type_size[sizeof (char)] = CHAR;
  1641.   integral_type_size[sizeof (short int)] = SHORT;
  1642.   integral_type_size[sizeof (int)] = INT;
  1643.   integral_type_size[sizeof (long int)] = LONG;
  1644.  
  1645.   for (i = 0; i <= MAX_FP_TYPE_SIZE; i++)
  1646.     fp_type_size[i] = NO_SIZE;
  1647.  
  1648.   fp_type_size[sizeof (float)] = FP_SINGLE;
  1649.   /* The array entry for `double' is filled in after that for LONG_DOUBLE
  1650.      so that if `long double' is the same type or if long double isn't
  1651.      supported FP_LONG_DOUBLE will never be used.  */
  1652.   fp_type_size[sizeof (LONG_DOUBLE)] = FP_LONG_DOUBLE;
  1653.   fp_type_size[sizeof (double)] = FP_DOUBLE;
  1654.  
  1655.   n_specs = 0;
  1656.   n_specs_allocated = 5;
  1657.   spec = (struct tspec *) xmalloc (n_specs_allocated * sizeof (struct tspec));
  1658.  
  1659.   output_address_fmt_string = "%07o";
  1660.   format_address = format_address_std;
  1661.   address_pad_len = 7;
  1662.   flag_dump_strings = 0;
  1663.  
  1664.   while ((c = getopt_long (argc, argv, "abcCdfhilos::xw::A:j:N:t:v",
  1665.                long_options, (int *) 0))
  1666.      != EOF)
  1667.     {
  1668.       strtoul_error s_err;
  1669.  
  1670.       switch (c)
  1671.     {
  1672.     case 0:
  1673.       break;
  1674.  
  1675.     case 'A':
  1676.       switch (optarg[0])
  1677.         {
  1678.         case 'd':
  1679.           output_address_fmt_string = "%07d";
  1680.           format_address = format_address_std;
  1681.           address_pad_len = 7;
  1682.           break;
  1683.         case 'o':
  1684.           output_address_fmt_string = "%07o";
  1685.           format_address = format_address_std;
  1686.           address_pad_len = 7;
  1687.           break;
  1688.         case 'x':
  1689.           output_address_fmt_string = "%06x";
  1690.           format_address = format_address_std;
  1691.           address_pad_len = 6;
  1692.           break;
  1693.         case 'n':
  1694.           output_address_fmt_string = NULL;
  1695.           format_address = format_address_none;
  1696.           address_pad_len = 0;
  1697.           break;
  1698.         default:
  1699.           error (2, 0,
  1700.              "invalid output address radix `%c'; it must be one character from [doxn]",
  1701.              optarg[0]);
  1702.           break;
  1703.         }
  1704.       break;
  1705.  
  1706.     case 'j':
  1707.       s_err = my_strtoul (optarg, 0, &n_bytes_to_skip, 1);
  1708.       if (s_err != UINT_OK)
  1709.         uint_fatal_error (optarg, "skip argument", s_err);
  1710.       break;
  1711.  
  1712.     case 'N':
  1713.       limit_bytes_to_format = 1;
  1714.  
  1715.       s_err = my_strtoul (optarg, 0, &max_bytes_to_format, 1);
  1716.       if (s_err != UINT_OK)
  1717.         uint_fatal_error (optarg, "limit argument", s_err);
  1718.       break;
  1719.  
  1720.     case 's':
  1721.       if (optarg == NULL)
  1722.         string_min = 3;
  1723.       else
  1724.         {
  1725.           s_err = my_strtoul (optarg, 0, &string_min, 1);
  1726.           if (s_err != UINT_OK)
  1727.         uint_fatal_error (optarg, "minimum string length", s_err);
  1728.         }
  1729.       ++flag_dump_strings;
  1730.       break;
  1731.  
  1732.     case 't':
  1733.       if (decode_format_string (optarg))
  1734.         error (2, 0, "invalid type string `%s'", optarg);
  1735.       break;
  1736.  
  1737.     case 'v':
  1738.       abbreviate_duplicate_blocks = 0;
  1739.       break;
  1740.  
  1741.     case 'C':
  1742.       flag_compatibility = 1;
  1743.       break;
  1744.  
  1745.       /* The next several cases map the old, pre-POSIX format
  1746.          specification options to the corresponding POSIX format
  1747.          specs.  GNU od accepts any combination of old- and
  1748.          new-style options.  Format specification options accumulate.  */
  1749.  
  1750. #define CASE_OLD_ARG(old_char,new_string)        \
  1751.     case old_char:                    \
  1752.       {                        \
  1753.         int tmp;                    \
  1754.         tmp = decode_format_string (new_string);    \
  1755.         assert (tmp == 0);                \
  1756.       }                        \
  1757.       break
  1758.  
  1759.       CASE_OLD_ARG ('a', "a");
  1760.       CASE_OLD_ARG ('b', "oC");
  1761.       CASE_OLD_ARG ('c', "c");
  1762.       CASE_OLD_ARG ('d', "u2");
  1763.       CASE_OLD_ARG ('f', "fF");
  1764.       CASE_OLD_ARG ('h', "x2");
  1765.       CASE_OLD_ARG ('i', "d2");
  1766.       CASE_OLD_ARG ('l', "d4");
  1767.       CASE_OLD_ARG ('o', "o2");
  1768.       CASE_OLD_ARG ('x', "x2");
  1769.  
  1770. #undef CASE_OLD_ARG
  1771.  
  1772.     case 'w':
  1773.       width_specified = 1;
  1774.       if (optarg == NULL)
  1775.         {
  1776.           desired_width = 32;
  1777.         }
  1778.       else
  1779.         {
  1780.           s_err = my_strtoul (optarg, 10, &desired_width, 0);
  1781.           if (s_err != UINT_OK)
  1782.         error (2, 0, "invalid width specification `%s'", optarg);
  1783.         }
  1784.       break;
  1785.  
  1786.     default:
  1787.       usage ();
  1788.       break;
  1789.     }
  1790.     }
  1791.  
  1792.   if (flag_version)
  1793.     {
  1794.       fprintf (stderr, "%s\n", version_string);
  1795.       exit (0);
  1796.     }
  1797.  
  1798.   if (flag_help)
  1799.     usage ();
  1800.  
  1801.   if (flag_dump_strings && n_specs > 0)
  1802.     error (2, 0, "no type may be specified when dumping strings");
  1803.  
  1804.   n_files = argc - optind;
  1805.  
  1806.   /* If the --compatible option is used, there may be from 0 to 3
  1807.      remaining command line arguments;  handle each case separately.
  1808.     od [file] [[+]offset[.][b] [[+]label[.][b]]]
  1809.      The offset and pseudo_start have the same syntax.  */
  1810.  
  1811.   if (flag_compatibility)
  1812.     {
  1813.       long int offset;
  1814.  
  1815.       if (n_files == 1)
  1816.     {
  1817.       if ((offset = parse_old_offset (argv[optind])) >= 0)
  1818.         {
  1819.           n_bytes_to_skip = offset;
  1820.           --n_files;
  1821.           ++argv;
  1822.         }
  1823.     }
  1824.       else if (n_files == 2)
  1825.     {
  1826.       long int o1, o2;
  1827.       if ((o1 = parse_old_offset (argv[optind])) >= 0
  1828.           && (o2 = parse_old_offset (argv[optind + 1])) >= 0)
  1829.         {
  1830.           n_bytes_to_skip = o1;
  1831.           flag_pseudo_start = 1;
  1832.           pseudo_start = o2;
  1833.           argv += 2;
  1834.           n_files -= 2;
  1835.         }
  1836.       else if ((o2 = parse_old_offset (argv[optind + 1])) >= 0)
  1837.         {
  1838.           n_bytes_to_skip = o2;
  1839.           --n_files;
  1840.           argv[optind + 1] = argv[optind];
  1841.           ++argv;
  1842.         }
  1843.       else
  1844.         {
  1845.           error (0, 0,
  1846.              "invalid second operand in compatibility mode `%s'",
  1847.              argv[optind + 1]);
  1848.           usage ();
  1849.         }
  1850.     }
  1851.       else if (n_files == 3)
  1852.     {
  1853.       long int o1, o2;
  1854.       if ((o1 = parse_old_offset (argv[optind + 1])) >= 0
  1855.           && (o2 = parse_old_offset (argv[optind + 2])) >= 0)
  1856.         {
  1857.           n_bytes_to_skip = o1;
  1858.           flag_pseudo_start = 1;
  1859.           pseudo_start = o2;
  1860.           argv[optind + 2] = argv[optind];
  1861.           argv += 2;
  1862.           n_files -= 2;
  1863.         }
  1864.       else
  1865.         {
  1866.           error (0, 0,
  1867.           "in compatibility mode the last 2 arguments must be offsets");
  1868.           usage ();
  1869.         }
  1870.     }
  1871.       else
  1872.     {
  1873.       error (0, 0,
  1874.          "in compatibility mode there may be no more than 3 arguments");
  1875.       usage ();
  1876.     }
  1877.  
  1878.       if (flag_pseudo_start)
  1879.     {
  1880.       static char buf[10];
  1881.  
  1882.       if (output_address_fmt_string == NULL)
  1883.         {
  1884.           output_address_fmt_string = "(%07o)";
  1885.           format_address = format_address_std;
  1886.         }
  1887.       else
  1888.         {
  1889.           sprintf (buf, "%s (%s)",
  1890.                output_address_fmt_string,
  1891.                output_address_fmt_string);
  1892.           output_address_fmt_string = buf;
  1893.           format_address = format_address_label;
  1894.         }
  1895.     }
  1896.     }
  1897.  
  1898.   assert (address_pad_len <= MAX_ADDRESS_LENGTH);
  1899.   for (i = 0; (unsigned) i < address_pad_len; i++)
  1900.     address_pad[i] = ' ';
  1901.   address_pad[address_pad_len] = '\0';
  1902.  
  1903.   if (n_specs == 0)
  1904.     {
  1905.       int d_err = decode_one_format ("o2", NULL, &(spec[0]));
  1906.  
  1907.       assert (d_err == 0);
  1908.       n_specs = 1;
  1909.     }
  1910.  
  1911.   if (n_files > 0)
  1912.     file_list = (char const *const *) &argv[optind];
  1913.   else
  1914.     {
  1915.       /* If no files were listed on the command line, set up the
  1916.      global array FILE_LIST so that it contains the null-terminated
  1917.      list of one name: "-".  */
  1918.       static char const *const default_file_list[] = {"-", NULL};
  1919.  
  1920.       file_list = default_file_list;
  1921.     }
  1922.  
  1923.   err |= skip (n_bytes_to_skip);
  1924.  
  1925.   pseudo_offset = (flag_pseudo_start ? pseudo_start - n_bytes_to_skip : 0);
  1926.  
  1927.   /* Compute output block length.  */
  1928.   l_c_m = get_lcm ();
  1929.  
  1930.   if (width_specified)
  1931.     {
  1932.       if (desired_width != 0 && desired_width % l_c_m == 0)
  1933.     bytes_per_block = desired_width;
  1934.       else
  1935.     {
  1936.       error (0, 0, "warning: invalid width %d; using %d instead",
  1937.          desired_width, l_c_m);
  1938.       bytes_per_block = l_c_m;
  1939.     }
  1940.     }
  1941.   else
  1942.     {
  1943.       if (l_c_m < DEFAULT_BYTES_PER_BLOCK)
  1944.     bytes_per_block = l_c_m * (int) (DEFAULT_BYTES_PER_BLOCK / l_c_m);
  1945.       else
  1946.     bytes_per_block = l_c_m;
  1947.     }
  1948.  
  1949. #ifdef DEBUG
  1950.   for (i = 0; i < n_specs; i++)
  1951.     {
  1952.       printf ("%d: fmt=\"%s\" width=%d\n",
  1953.           i, spec[i].fmt_string, width_bytes[spec[i].size]);
  1954.     }
  1955. #endif
  1956.  
  1957.   err |= (flag_dump_strings ? dump_strings () : dump ());
  1958.  
  1959.   if (have_read_stdin && fclose (stdin) == EOF)
  1960.     error (2, errno, "standard input");
  1961.  
  1962.   if (fclose (stdout) == EOF)
  1963.     error (2, errno, "write error");
  1964.  
  1965.   exit (err);
  1966. }
  1967.